<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/19
 * Time: 14:22
 */

namespace app\index\controller;


use app\common\controller\PayBase;
use app\index\model\ChongzhiList;
use think\Db;
use think\Exception;

class Payqyzf extends PayBase{
    protected $uid;
    protected $key;
    protected $pay_url;
    protected $back_url;
    protected $href_url;

    public function __construct() {
        parent::__construct();
//        $this->uid = '5484';
        $this->uid = '5528';
//        $this->key = '64fa0cdacc2c4b55b5d59290daa55dda';
        $this->key = 'c1166a23a57b40c6b69fb4ad027fc2db';
        $this->pay_url = 'https://www.qianyingnet.com/pay/';
        $this->back_url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index/Payqyzf/callBack';
        $this->href_url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index/Payqyzf/hrefUrl';
    }
    public function initPay($username='',$pay_type='',$amount=-1,$from=0){
        //接收数据
        $user = cookie('username','');
        $password = cookie('password','');
        $username =  empty($username) ? input('post.username','') : $username;
        $pay_type = empty($pay_type) ? input('post.pay_type','') : $pay_type;
        $amount = -1==$amount ? input('post.amount',0) : $amount;
        $ctime = time();

        if($pay_type=='null' || $pay_type=='') return packJson('',$pay_type.'请选择支付方式',500);
        $pay_method = Db::name('pay_type_list')
            ->alias("a")
            ->join('__PAY_METHOD__ b','a.method_id=b.id','LEFT')
            ->where(['a.method'=>10,'a.type_value'=>$pay_type])
            ->field('a.type_name,b.name,b.id,b.method,b.money')->find();
        $remark = $pay_method['type_name'].'-'.$pay_method['name'];
        //验证用户信息
        if( 0==$from ){
            if(!$user || !$username || ($user!=$username)) return packJson('','用户身份验证失败',500);
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username,'password'=>$password])->find();
        }else{
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username])->find();
        }
        if(!$user_info) return packJson('','用户身份验证失败',500);
        if($user_info['swzh'] == 1) return packJson('','试玩账号无法充值',500);
        if($user_info['nbzh'] == 1) return packJson('','内部账号不支持线上充值',500);

        //充值防骚扰是否开启，并进行处理
        $harassment = Db::name('xt_czfsr')->find();
        if($harassment['open'] > 0) {
            $nowys = $ctime - $harassment['time_xs'] * 60;
            $old_czjl = Db::name('chongzhi_list')->where('username',$username)->where('cztime','>',$nowys)->find();
            if($old_czjl['id'] > 0) {
                return packJson('',"系统充值防骚扰已开启，{$harassment['time_xs']}分钟内只能充值1次！",500);
            }
        }
        //验证金额
        //        if($amount <= 0) return packJson('','请输入充值金额',500);
        //        if($amount < 10) return packJson('','最低充值金额为十元人民币',500);
        //        if($amount > 5000) return packJson('','充值金额超过范围',500);

        //计算优惠金额
        $msje = $msbs = 0;
        $cz_set = Db::name('xt_chongzhi')->find();
        $user_class = Db::name('us_class')->where('id',$user_info['us_class'])->find();
        $zsje = $amount * $user_class['czzsbl'] / 100;
        $zsbs = $user_class['czzsbl'];
        if($amount >= $cz_set['xscz_je']) {
            $msje = $amount * $cz_set['xscz_zs'] / 100;
            $msbs = $cz_set['xscz_zs'];
        }
        //充值方案赠送
        $method_money = 0.00;
        if( floatval( $pay_method['money'] ) > 0 ){
            if( 0==intval( $pay_method['method'] ) ){
                //金额
                $method_money = $pay_method['money'];
            }else{
                //比例
                $method_money = floatval($amount) * floatval($pay_method['money']) / 100;
            }
        }
        $method_money = sprintf("%.2f",substr(sprintf("%.3f", $method_money), 0, -2));

        //生成订单号
        $order_sn = 'QYF' . str_pad($user_info['id'],5,'0',STR_PAD_LEFT) . $ctime . rand(111,999);
        //组装数据
        if( 1==$from ) $this->href_url.="Third";
        $data = [
            'uid' => $this->uid,
            'type' => $pay_type,
            'm' => $amount,
            'orderid' => $order_sn,
            'callbackurl' => $this->back_url
        ];

        $sign = self::signature($data,$this->key);
        $data['sign'] = $sign;
        $data['gofalse'] = $this->href_url.'False';
        $data['gotrue'] = $this->href_url.'True';
        $data['charset'] = 'utf-8';
        $data['uuid'] = $username;  //唯一标识,支付宝或微信
        $u = Db::name('username')->where('username',$username)->value('je');
        $model = new ChongzhiList();
        if( $model->setTransRechargeInfo($order_sn,$amount,$username,0,0,1,$remark,$ctime,'千应线上支付','系统自动',get_ip(),0,$pay_type,$zsje,$zsbs,$msje,$msbs,$user_info['us_class'],'',0,$method_money,$u) ){
            $pay_url = $this->pay_url . '?' . http_build_query($data);
            return packJson($pay_url,'',200);
        }else{
            return packJson('',"订单生产错误",500);
        }
    }
    public function callBack(){
        Db::startTrans();
        $orderid = input('oid','');         //订单号
        $status = input('status','');   //处理结果：【1：支付完成；2：超时未支付，订单失效；4：处理失败，详情请查看msg参数；5：订单正常完成（下发成功）；6：补单；7：重启网关导致订单失效；8退款】
        $money = input('m1',0);            //实际充值金额
        $sign = input("sign",'');          //签名，用于校验数据完整性
        $orderidMy = input("oidMy",'');    //千应录入时产生流水号，建议保存以供查单使用
        $orderidPay = input("oidPay",'');  //收款方的订单号（例如支付宝交易号）;
        $completiontime = input("time",'');//千应处理时间
        $attach = input("uuid",'');       //上行附加信息
        $param="oid=".$orderid."&status=".$status."&m=".$money.$this->key;  //拼接$param
        $paramMd5   =  md5($param);          //md后加密之后的$param
        if(strcasecmp($sign,$paramMd5)==0){
            if($status == "1" || $status == "5" || $status == "6"){
                //可在此处增加操作数据库语句，实现自动下发，也可在其他文件导入该php，写入数据库
                $order_info = Db::name('chongzhi_list')->where('ddbh',$orderid)->find();
//                if($order_info['je'] != $money) return '金额不一致';
                $user_info = Db::name('username')->where('username',$attach)->find();
                $dml_set = Db::name('xt_dmsz')->where('id',1)->find();
                $xtcz = Db::name('xt_chongzhi')->where('id',1)->find();
                if($xtcz['dmopen'] == 1) {
                    $dmls = ($order_info['hy_msje'] + $order_info['hy_zsje'] + $order_info['je']+ $order_info['method_money']) * $dml_set['xscz_dmbs'];
                }else{
                    $dmls = $order_info['je'] * $dml_set['xscz_dmbs'];
                }
                //充值后账户总金额
                $czhje = $order_info['hy_msje'] + $order_info['hy_zsje'] + $order_info['je'] + $user_info['je']+ $order_info['method_money'];
                //充值总金额
                $czzje = $order_info['je'] + $user_info['czzje'];
                //用户当前打码量
                $dml = $user_info['dml'] + $dmls;
                try {
                    $zt = model('ChongzhiList')->where(['ddbh'=>$orderid])->value('zt');
                    if( 1==intval($zt) ){
                        throw new Exception("该订单已经成功通知");
                    }
                    if( !model('ChongzhiList')->updateRechargeInfo($orderid,$orderidPay,1,$czhje,strtotime($completiontime)) ){
                        throw new Exception("更新订单信息错误");
                    }
                    if( !model('Username')->upUserXsczInfo($czhje,$dml,$czzje,$attach) ){
                        throw new Exception("更新用户金额错误");
                    }
                    Db::name('username')->where('username',$order_info['username'])->setInc('cz_num');
                    $fav_money = $order_info['hy_msje']+$order_info['hy_zsje']+ $order_info['method_money'];

                    //满送金额，等级赠送金额，充值方案赠送金额
                    $extcj = array(
                        'username'=>$user_info['username'],
                        'user_class'=>$user_info['us_class'],
                        'fstime'=>time(),
                        'czadmin' => '系统赠送',
                    );
                    $cjhje = floatval($order_info['je']) + floatval($user_info['je']) + floatval($order_info['hy_msje']);
                    if( floatval($order_info['hy_msje']) > 0 ){
                        $extcj['beizhu'] = '系统赠送，充值满送金额';
                        $extcj['cjje'] = $order_info['hy_msje'];
                        $extcj['cjhje'] = $cjhje;
                        Db::name('caijin_list')->insert($extcj);
                    }
                    $cjhje += floatval($order_info['hy_zsje']);
                    if( floatval($order_info['hy_zsje']) > 0 ){
                        $extcj['beizhu'] = '系统赠送，充值等级赠送金额';
                        $extcj['cjje'] = $order_info['hy_zsje'];
                        $extcj['cjhje'] = $cjhje;
                        Db::name('caijin_list')->insert($extcj);
                    }
                    $cjhje += floatval($order_info['method_money']);
                    if( floatval($order_info['method_money']) > 0 ){
                        $extcj['beizhu'] = '系统赠送，充值方案赠送金额';
                        $extcj['cjje'] = $order_info['method_money'];
                        $extcj['cjhje'] = $cjhje;
                        Db::name('caijin_list')->insert($extcj);
                    }

                    $data = array('username' =>$attach,'test'=>"您账户充值金额：{$order_info['je']}，赠送金额：{$fav_money}。已充值到账，请注意查收！",'xx_time'=>strtotime($completiontime),'ifdq'=>0);
                    Db::name('xiaoxi')->data($data)->insert();
                    Db::commit();
                    echo "success";
                } catch (\Exception $e) {
                    Db::rollback();
                    echo "订单处理失败";
                }
            }else if($status == "4"){
                echo "订单处理失败";
            }else if ($status == "8"){
                echo "订单已经退款！";
            }else{
                echo "订单处理失败";
            }
        }else{
            echo "签名无效，视为无效数据!";
        }
    }
    public function hrefUrlFalse(){
        $this->buildHtml("充值失败");
    }
    public function hrefUrlTrue(){
        $this->buildHtml("充值成功");
    }
    public function hrefUrlThirdFalse(){
        $this->buildHtml("充值失败",1);
    }
    public function hrefUrlThirdTrue(){
        $this->buildHtml("充值成功",1);
    }
    private function signature($params=[],$key){
        $clear_text='';
        foreach ($params as $k=>$v){
            $clear_text .= $k.'='.$v.'&';
        }
        $clear_text = trim($clear_text,'&');
        $cipher_text = md5($clear_text.$key); //计算md5 hash
        return $cipher_text;
    }
}